import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/widget/common/count_text.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import 'package:material_collection_app/widget/common/search_box.dart';
import 'package:material_collection_app/widget/common/top_bar.dart';
import 'package:material_collection_app/widget/new/AddMaterial.dart';
import 'package:material_collection_app/widget/new/NewMaterialCard.dart';
import '../utils/utils.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class AddMaterialPage extends StatefulWidget {
  final Map arguments;
  AddMaterialPage({Key key, this.arguments}) : super(key: key);

  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<AddMaterialPage> {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  List list = [];
  Map obj = {};
  bool loadSuccess = false;
  String keywords = '';

  @override
  void initState() {
    super.initState();
  }

  Widget _buildPage() {
    // // 无数据
    if (list.length == 0) {
      return EmptyTips(
        refreshController: _refreshController,
        backgroundColor: Utils.hexToColor('#F7F6F9'),
      );
    }

    return ListView.builder(
        itemCount: list.length,
        padding: EdgeInsets.only(bottom: 60.w),
        itemBuilder: (BuildContext context, int index) {
          if (keywords == '') {
            return NewMaterialCard(item: list[index]);
          } else if (keywords != '' && keywords == list[index]['name']) {
            return NewMaterialCard(item: list[index]);
          } else {
            return Container();
          }
        });
  }

  // 添加物资
  Future<void> showAddMaterialDialog(String type, {Map item}) async {
    showDialog(
        context: context,
        builder: (context) {
          return Dialog(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12.w))),
              insetPadding: EdgeInsets.all(0),
              child: AddMaterial(
                item: item,
                onSubmit: (e) {
                  _addMaterialLocal(e);
                },
              ));
        });
  }

  // 添加物资到本地
  _addMaterialLocal(data) {
    List arr = list;
    arr.add(data);

    setState(() {
      list = arr;
    });
    print(list);
    print(keywords == '');
  }

  _submit() {
    // String caseNo = widget.arguments['case_no'];
    String caseName = widget.arguments['case_name'];
    int depId = widget.arguments['department_id'];
    String subTime = widget.arguments['submission_time'];
    // int storeId = widget.arguments['store_id'];
    // int libId = widget.arguments['library_id'];
    String remark = widget.arguments['remark'];
    int depUId = widget.arguments['depUId'];

    DioUtils.request("enter/save", context: context, method: "POST", params: {
      // 'case_no': caseNo,
      'case_name': caseName,
      'department_id': depId,
      'submission_time': subTime,
      // 'store_id': storeId,
      // 'library_id': libId,
      'remark': remark,
      'material': list,
      'department_union_id': depUId
    }, onSuccess: (res) {
      Utils.showText(text: res['msg']);

      if (res['code'] == 1) {
        Future.delayed(Duration(seconds: 1), () {
          Navigator.of(context).pop();
          Navigator.of(context).pop();
        });
      }
    }, onError: (error) {});
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Scaffold(
        appBar: TopBar(
          height: 0,
        ),
        body: Container(
            color: Utils.hexToColor('#F5F6FA'),
            child: Column(children: <Widget>[
              SearchBox(
                hintText: '名称',
                endDrawer: true,
                onSearch: (value) {
                  setState(() {
                    keywords = value;
                  });
                },
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: 85,
                    height: 30,
                    margin: EdgeInsets.only(left: 25.w, top: 10),
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                          backgroundColor: Utils.hexToColor('#297CFF'),
                          padding: EdgeInsets.all(0)),
                      onPressed: () {
                        this.showAddMaterialDialog('add');
                      },
                      child: Text(
                        '添加物资',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                  CountText(number: list.length),
                ],
              ),
              Expanded(
                  child: Container(
                      padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
                      child: _buildPage())),
              Offstage(
                offstage: list.length > 0 ? false : true,
                child: Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                        margin: EdgeInsets.only(bottom: 20.w),
                        child: SizedBox(
                            width: 700.w,
                            height: 110.w,
                            child: ElevatedButton(
                              onPressed: () {
                                _submit();
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Image.asset('assets/submit.png', width: 12),
                                  Container(
                                    margin: EdgeInsets.only(left: 8),
                                    child: Text(
                                      '提交',
                                      style: TextStyle(color: Colors.white),
                                    ),
                                  )
                                ],
                              ),
                              style: ElevatedButton.styleFrom(
                                  backgroundColor: Color(0xFF297CFF),
                                  shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(60.w)))),
                            )))),
              )
            ])));
  }
}
